import React, { PureComponent } from 'react';
interface SendData {
    source: 'ceair-auto-fixed',
    reply?: boolean,
    data?: any,
    cmd?: string,
}
class MessageHoc extends PureComponent<{ children: (data: any, connectStatus: boolean) => React.ReactNode }, {
    data: any,
    isConnect: boolean,
}> {
    constructor(props: any) {
        super(props);
        this.state = {
            data: undefined,
            isConnect: false,
        };
    }
    componentDidMount() {
        window.addEventListener('message', this.receiveMessage.bind(this), false);
    }
    componentWillUnmount() {
        window.removeEventListener('message', function (e) { }, false);
    }

    receiveMessage(e: MessageEvent) {
        if (e.origin.includes('http://www.ceair.com') && e.data.source === "ceair-auto-content-script") {
            console.log('receiveMessage.......', e.data);
            const { isConnect } = this.state;
            if (e.data.hello && !isConnect) {
                console.log('接收到请求');
                this.setState({
                    isConnect: true,
                }, () => {
                    (e.source as MessagePort).postMessage({ source: 'ceair-auto-fixed', reply: true } as SendData);
                })
                return;
            } else if (typeof (e.data.connect) === 'boolean') {
                console.log('接收到数据1', e.data.data);
                this.setState({
                    data: e.data.data,
                    isConnect: e.data.connect,
                });

            }

        }
    }
    render() {
        const { children } = this.props;
        if (typeof (children) === 'function') {
            return children(this.state.data, this.state.isConnect);
        }
        throw new Error('children is not function. for Example,()=><div />')
        // return <>
        //     <Btns dataSource={this.state.sourceData} intervalTime={this.state.intervalTime} />
        // </>
    }
}
export default MessageHoc;